/*!
  \file
  Header file for a simple HHV on the GPU
*/

/*
  Copyright (c) 2011, President & Fellows of Harvard College
  All rights reserved.
  
  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  
  * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  * Neither the name of the Harvard College nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#ifndef SCIGPU_HHV_HHVOLUME_SIMPLE_GPU_HPP
#define SCIGPU_HHV_HHVOLUME_SIMPLE_GPU_HPP

#include <cuda_runtime.h>

#include "cudahostbuffer.hpp"

#include "hhvolume.hpp"
#include "objectconvertor.hpp"

namespace SciGPU {
  namespace HHV {

    //! Hypervolume on the GPU
    /*!
      This class implements a hypervolume on the GPU.
      By default, the internal buffer will be of type CUDAhostBuffer, and make
      use of pinned host memory, to speed transfers.
      @bug Should define own exceptions
    */
    template<typename T, unsigned int nDims>
    class HHVolumeGPU : public HHVolume<T,nDims> {
    public:
      //! Convertor type
      typedef ObjectConvertor< HHVolumeGPU<T,nDims>,
			       HHVolume<T,nDims> > convertor;

      //! Constructor with buffer
      HHVolumeGPU( const BufferObject<T>& buff = CUDAhostBuffer<T,cudaHostAllocDefault>() )
        : HHVolume<T,nDims>(buff),
          d_data(NULL),
          bytesAllocated(0) {};

      //! Destructor
      virtual ~HHVolumeGPU( void ) {
        this->ReleaseDevice();
      }

      // ------------------------------------

      //! Send data to the GPU
      virtual void Send( void ) {
        /*!
          This method makes use of \c cudaMemcpy to transfer
          data from the internal buffer to the GPU.
          If the transfer fails, an exception of type
          \c std::runtime_error will be thrown.
          Ideally, this would wrap an asynchronous transfer.
        */
        cudaError_t err;
        err = cudaMemcpy( this->d_data,
                          this->buffer->start(),
                          this->hyxels()*sizeof(T),
                          cudaMemcpyHostToDevice );
        if( cudaSuccess != err ) {
          throw std::runtime_error( "cudaMemcpy failed" );
        }
      }

      //! Retrieve data from the GPU
      virtual void Recv( void ) const {
        /*!
          Uses \c cudaMemcpy to transfer data back to the
          internal buffer.
          If the transfer fails, an exception of type
          \c std::runtime_error will be thrown.
        */
        cudaError_t err;
        err = cudaMemcpy( this->buffer->start(),
                          this->d_data,
                          this->hyxels()*sizeof(T),
                          cudaMemcpyDeviceToHost );
        if( cudaSuccess != err ) {
          throw std::runtime_error( "cudaMemcpy failed" );
        }
      }
  
      // ----------------------------------

      //! Access the data on the GPU (const)
      virtual const T* start( void ) const {
        return( this->d_data );
      }

      //! Access the data on the GPU
      virtual T* start( void ) {
        return( this->d_data );
      }


    protected:
      //! The actual GPU data;
      T* d_data;
      //! The size of the allocation on the GPU
      size_t bytesAllocated;

      //! Allocation on the GPU
      virtual void AllocateDevice( const DimensionObject<nDims>& myDims ) {
        /*!
          Allocates GPU memory to hold the specified size of hypervolume.
          If the allocation (via \c cudaMalloc) fails, an instance of
          \c std::runtime_error will be thrown.
          Prior to allocation, the current size of the allocation
          is checked.
          So long as the required allocation is smaller, the old allocation
          is maintained.
        */
        const size_t bytesReq = myDims.hyxels() * sizeof(T);

        if( bytesReq <= this->bytesAllocated ) {
          return;
        }

        this->ReleaseDevice();

        cudaError_t err;
        err = cudaMalloc( &(this->d_data), bytesReq );
        if( cudaSuccess != err ) {
          throw std::runtime_error( "cudaMalloc failed" );
        }

        this->bytesAllocated = bytesReq;
      }

      //! Release of memory on the GPU
      void ReleaseDevice( void ) {
        if( this->d_data != NULL ) {
          cudaError_t err;
          err = cudaFree( this->d_data );
          if( cudaSuccess != err ) {
            throw std::runtime_error( "cudaFree failed" );
          }

          this->d_data = NULL;
          this->bytesAllocated = 0;
        }
      }

    private:

    };

  }
}

#endif
